#include "ImageModel.h"



ImageModel* ImageModel::instance = nullptr;


ImageModel::ImageModel(QObject *parent) : QAbstractListModel(parent) {
}


ImageModel::~ImageModel() {
    delete instance;
}



QHash<int, QByteArray> ImageModel::roleNames() const{
    QHash<int, QByteArray> roles;
    roles[1] = "imageName";
    return roles;
}


int ImageModel::rowCount(const QModelIndex &parent) const {
    Q_UNUSED(parent);
    return _dataList_.count();

}


QVariant ImageModel::data(const QModelIndex &index, int role) const {
    int row = index.row();
    if(row < 0 || row >= _dataList_.count()) {
        return QVariant();
    }
    QString fileName = _dataList_[row];
    return fileName;
}

QString ImageModel::get(const int &index) {
    if(index < 0 || index >= _dataList_.count()) {
        throw "ImageModel._dataList_数组下标越界:"+ QString::number(index);
    }
    return _dataList_[index];
}


BaseResult::JsonResult ImageModel::openDir(QString dir) {
    if(this->savePath.isNull() || this->savePath.isEmpty()) {
        return BaseResult(BaseResult::FAILED, "未选择保存路径,请先选择").toJson();
    }
    this->dir = dir.mid(8);
    QDir* dir_ptr = new QDir(this->dir);
    if (!dir_ptr->exists()) {
        delete dir_ptr;
        dir_ptr = nullptr;
        return BaseResult(BaseResult::FAILED, "文件目录不存在").toJson();
    }

    dir_ptr->setNameFilters(QStringList({"*.png", "*.jpg", "*.jpeg", "*.bmp"}));
    QStringList fileList = dir_ptr->entryList(QDir::Files);
    emit beginResetModel();
    _dataList_.clear();
    for(QString file: fileList) {
        _dataList_.append(file);
    }
    emit endResetModel();
    ImageLabelModel::setImageName(this->dir + "/" + this->_dataList_[0]);
    return BaseResult(BaseResult::SUCCEED, "打开成功").toJson();
}


int ImageModel::count() const {
    return rowCount(QModelIndex());
}


void ImageModel::setSavePath(QString savePath) {
    this->savePath = savePath.mid(8);
    ImageLabelModel::setImageLabelSaveFilePath(this->savePath);
}


QString ImageModel::getImageName(int index){

    if(index < 0 || index >= _dataList_.count()) {
        return "";
    }
    return  this->dir + "/" + this->_dataList_[index];

}


QString ImageModel::getImageLabelSaveFilePath(int index) {
    if(index < 0 || index >= _dataList_.count() || this->savePath.isNull() || this->savePath.isEmpty()) {
        return "";
    }
    return  this->savePath;

}

